package com.example.demo.controller;

import com.example.demo.model.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.Session;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.UUID;

@Slf4j
@Controller
@RequestMapping("/user")  //一级目录(类上可以省略)  方法上是二级目录
@ResponseBody
public class UserController {

    @ResponseBody    //如果不加默认返回一个静态页面(比如前面写的blog_list.html),例如下面,不加会去找页面为"你好,世界"
    @RequestMapping("/sayhi")   //默认支持get,post方法请求(浏览器默认是get请求)
    public String sayHi() {
        return "陶俊臣";         //热部署测验(不用重新重启)
    }

    @RequestMapping(method = RequestMethod.POST,value = "/sayhi2")  //定义了这个就只支持post请求
    public String sayHi2() {
        return "hello world 2.";
    }

    /**
     * 只支持post请求
     * @return
     */
    @PostMapping("/sayhi3")
    public String sayHi3() {
        return "hello world 3 .";
    }

    /**
     * 只支持get请求
     * @return
     */
    @GetMapping ("/sayhi4")
    public String sayHi4() {
        return "hello world 4 .";
    }


    //获取一个参数
    @RequestMapping("/getuserbyid")
    public UserInfo getUserById(Integer id) {   //最好用包装类,拿不到参数情况可以为null,下面做校验就好
        //伪代码
        UserInfo userInfo = new UserInfo();
        userInfo.setId(id);
        userInfo.setUsername("陶俊臣");
        userInfo.setAge(20);
        return userInfo;
    }


    //获取两个参数
    @RequestMapping("/login")
    public String login(@RequestParam(value = "name",required = false) String username,String password) {  //参数重命名(false表示前端可以不传)
        return "用户名"+username+" | 密码:"+password;
    }

    //通过对象返回
    @RequestMapping("/reg")   //要接收json格式的数据需要加注解(默认不能获取到json) @RequestBody
    public String reg(@RequestBody UserInfo userInfo) {
        return "用户信息:"+userInfo;
    }

    @RequestMapping("/find/{name}/{id}")   //从URL中接收参数
    public String find(@PathVariable String name,@PathVariable Integer id) {
        return "name:"+name+" | id: " +id+"";
    }

    @Value("${img.path}")
    private String imgPath;  //拿到开发环境img存放的地址
    //上传一个图片到本机目录,用postman验证
    @RequestMapping("/upimg")
    public boolean upImg(Integer id, @RequestPart("img") MultipartFile file) {
        //伪代码
        boolean result = false;
        String filename = file.getOriginalFilename();  //拿到原始名称,包含后缀,sub方法切割
        filename = filename.substring(filename.lastIndexOf("."));   //拿到图片原本格式的后缀(png)
        filename = UUID.randomUUID().toString()+filename;    //UUID产生一个全球唯一id弄成图片名称(类似扣扣截图的一大串)
        try {
            file.transferTo(new File(imgPath+filename));
            result = true;
        } catch (IOException e) {
            log.error("上传图片失败,原因是"+e.getMessage());
        }
        return result;
    }

    @RequestMapping("/cookie")   //读取cookie数据
    public String getCookie(@CookieValue("bite") String cookie) {
        return "cookie :"+cookie;
    }

    @RequestMapping("/cookie2")   //HttpServletRequest拿取cookie数据(拿取多个)
    public void getCookie(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        for (Cookie item:cookies) {
            log.info("cookie name"+item.getName()+"cookie value"+item.getValue());
        }
    }

    @RequestMapping("/getua")    //读取Head中信息
    public String getHead(HttpServletRequest request) {
        return "Header中UA信息:  "+request.getHeader("User-Agent");
    }

    @RequestMapping("/getua1")   //读取Head中信息
    public String getHead1(@RequestHeader("User-Agent") String ua) {
        return "Header中UA信息:"+ua;
    }

    @RequestMapping("/setsession")   //存储session
    public String setSession(HttpServletRequest request) {
        HttpSession session = request.getSession(true);
        if(session != null) {
            session.setAttribute("username","java");
        }
        return "session 存储成功";
    }
    @RequestMapping("/getsession")   //读取session
    public String getSession(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        String username = "空白";
        if(session != null && session.getAttribute("username") != null) {
            username = (String) session.getAttribute("username");   //拿到value
        }
        return "username: "+username;
    }

    @RequestMapping("getsession1")
    public String getSession1(@SessionAttribute(value = "username",required = false) String username){
        //requiered为false可以保证为空不会报错导致程序停止,如果为true会导致程序停止(因为true为必传参数,没有就报错)
        return "username "+username;
    }

    @RequestMapping("/login1")
    public HashMap<String, Object> login1(String username, String password) {
//        if(username.equals("admin") && password.equals("admin")) {
//            return "登陆成功";
//        }
//        return "登陆失败";
        HashMap<String, Object> result = new HashMap<String, Object>();
        int state = 200;
        int data = -1; // 等于 1，登录成功，否则登录失败
        String msg = "未知错误";
        if (StringUtils.hasLength(username) && StringUtils.hasLength(password)) {
            if (username.equals("admin") && password.equals("admin")) {
                data = 1;
                msg = "";
            } else {
                msg = "用户名或密码失败！";
            }
        } else { // 参数为空
            msg = "非法参数";
        }
        result.put("state", state);
        result.put("data", data);
        result.put("msg", msg);
        return result;
    }

    @RequestMapping("/login2")
    public String login2(@RequestBody UserInfo userInfo) {
        if(StringUtils.hasLength(userInfo.getUsername()) && StringUtils.hasLength(userInfo.getPassword())) {
            if(userInfo.getUsername().equals("admin") && userInfo.getPassword().equals("admin")) {
                return "登陆成功";
            }
        }
        return "登陆失败";
    }
}
